package com.qiu.demo.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qiu.demo.entity.User;
import com.qiu.demo.entity.dto.LoginDto;
import com.qiu.demo.entity.dto.PwdDto;
import com.qiu.demo.entity.dto.UserProfileDto;
import com.qiu.demo.entity.vo.UserInfo;
import com.qiu.demo.enums.HttpCodeEnum;
import com.qiu.demo.service.UserService;
import com.qiu.demo.service.impl.UserServiceImpl;
import com.qiu.demo.util.JsonResult;
import com.qiu.demo.util.TokenUtil;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    private final String URL = "http://localhost:8080/";

    @Value("${file.path}")
    private String filePath;

    private final UserServiceImpl userServiceImpl;
    @Autowired
    private UserService userService;

    @Resource
    private TokenUtil tokenUtil;

    UserController(UserServiceImpl userServiceImpl) {
        this.userServiceImpl = userServiceImpl;
    }

    @PatchMapping("update/avatar")
    public JsonResult updateAvatar(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        // 获取项目classes/static的地址
        String path = filePath;
        String fileName = file.getOriginalFilename(); // 获取文件名
        // 图片访问URI(即除了协议、地址和端口号的URL)
        String url_path = "image" + File.separator + fileName;
        String savePath = path + File.separator + url_path; // 图片保存路径
        File saveFile = new File(savePath);

        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }
        try {
            file.transferTo(saveFile); // 将临时存储的文件移动到真实存储路径下
            Map userData = tokenUtil.parseToken(request.getHeader("Authorization"));
            String userId = userData.get("userId").toString();

            userService.update(
                    new LambdaUpdateWrapper<User>().eq(User::getUserId, userId).set(User::getAvator, URL + url_path));
        } catch (IOException e) {
            e.printStackTrace();
            return JsonResult.error().codeAndMessage(HttpCodeEnum.ERROR);
        }

        // 返回图片访问地址
        return JsonResult.success();
    }

    @GetMapping("userinfo")
    public JsonResult userinfo(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Map tokenData = tokenUtil.parseToken(token);
        String userId = tokenData.get("userId").toString();
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUserId, userId),
                false);
        if (user == null) {
            return JsonResult.error().codeAndMessage(HttpCodeEnum.RC103);
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setEmail(user.getEmail());
        userInfo.setNickname(user.getNickname());
        userInfo.setUser_pic(user.getAvator());
        userInfo.setUsername(user.getUsername());
        return JsonResult.success().data("userinfo", userInfo);
    }

    @PutMapping("userinfo")
    public JsonResult updateUserInfo(@RequestBody UserProfileDto userProfile, HttpServletRequest request) {
        Map userData = tokenUtil.parseToken(request.getHeader("Authorization"));
        String userId = userData.get("userId").toString();

        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getUserId, userId);

        if (StringUtils.hasText(userProfile.getNickname())) {
            updateWrapper.set(User::getNickname, userProfile.getNickname());
        }
        if (StringUtils.hasText(userProfile.getEmail())) {
            updateWrapper.set(User::getEmail, userProfile.getEmail());
        }

        userService.update(updateWrapper);

        return JsonResult.success();
    }

    @PatchMapping("updatepwd")
    public JsonResult updatepwd(@RequestBody PwdDto pwdDto, HttpServletRequest request) {
        Map userData = tokenUtil.parseToken(request.getHeader("Authorization"));
        String userId = userData.get("userId").toString();
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getUserId, userId);

        updateWrapper.set(User::getPassword, pwdDto.getNew_pwd());

        userService.update(updateWrapper);

        return JsonResult.success();
    }
}